from flask import jsonify, request, Blueprint
from ..recommend.ai import ai_recommendations
from ..recommend.bestseller import bestseller_recommendations
from ..recommend.discovery import discovery_recommendations
from ..recommend.featured import featured_recommendations
from ..recommend.guess import guess_recommendations
from ..recommend.highRating import highRating_recommendations
from ..recommend.hot import hot_recommendations
from ..recommend.newRelease import newRelease_recommendations
from ..recommend.poetry import poetry_recommendations
from ..recommend.popular import popular_recommendations
from ..recommend.premium import premium_recommendations
from ..recommend.publisherChoice import publisherChoice_recommendations
from ..recommend.recommend import recommend_recommendations

recommend_bp = Blueprint('recommend', __name__)

# 定义推荐类型到函数的映射
RECOMMENDATION_FUNCTIONS = {
    'recommend': recommend_recommendations,
    'premium': premium_recommendations,
    'popular': popular_recommendations,
    'hot': hot_recommendations,
    'discovery': discovery_recommendations,
    'guess': guess_recommendations,
    'featured': featured_recommendations,
    'ai': ai_recommendations,
    'bestseller': bestseller_recommendations,
    'highRating': highRating_recommendations,
    'newRelease': newRelease_recommendations,
    'poetry': poetry_recommendations,
    'publisherChoice': publisherChoice_recommendations
}


@recommend_bp.route('/recommend', methods=['GET'])
def get_recommendations():
    type = request.args.get('type')
    id = request.args.get('id')
    # 获取对应的推荐函数
    recommendation_func = RECOMMENDATION_FUNCTIONS.get(type)

    if not recommendation_func:
        return jsonify({
            'code': 400,
            'message': f'Invalid recommendation type: {type}',
            'data': []
        }), 400

    try:
        books = recommendation_func(id)
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'Recommendation failed: {str(e)}',
            'data': []
        }), 500

        # 格式化返回数据
    result = [{
        'id': str(book['_id']),
        'title': book.get('title', ''),
        'author': book.get('author', ''),
        'cover': book.get('cover', '')
    } for book in books]
    return jsonify({
        'code': 200,
        'message': 'success',
        'data': result
    })
